/*
 * Created on Jul 5, 2005
 *
 */
package com.erclab.internal.xpresso.formelements;

import com.erclab.internal.xpresso.conf.Settings;
import com.erclab.internal.xpresso.dataAccess.GenericResultSet;
import com.erclab.internal.xpresso.dataAccess.Query;
import com.erclab.internal.xpresso.exceptions.DataSourceException;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.forms.Form;

/**
 * @author Enrique Rodriguez.
 *
 */
public class SimpleMultiSelect extends DropDown {

	public String[] originalValues;
	
	public String toHTML(Form theForm){
		StringBuffer sb = new StringBuffer();
		sb.append("<SELECT name=\"Field");
		sb.append(this.idFormElement);
		sb.append("\"");
		sb.append(" id=\"" + this.destinationColumn + "\" onChange=\"formElementChanged(this)\" multiple>");
		
		for (int i =0; i < display.length; i++){
			sb.append("<OPTION VALUE=" + '"' + value[i] + '"');
			if(isSelectedValue(value[i])){
				sb.append(" selected>" + display[i] + "</OTPION>");
			} else {
				sb.append(">" + display[i] + "</OTPION>\n");
			}
		}
		sb.append("</SELECT>");
		return sb.toString();
	}
	
	/**
	 * @param string
	 * @return
	 */
	private boolean isSelectedValue(String value) {
		if (originalValues == null)
			return false;
		
		for (int i =0; i < this.originalValues.length; i++){
			if(value != null && value.equalsIgnoreCase(this.originalValues[i])){
				return true;
			}
		}
		return false;
	}

	public boolean isMultipleValue(){
		return true;
	}



	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.formelements.FormElement#loadOriginalValue(com.erclab.internal.xpresso.forms.Form)
	 */
	public void loadOriginalValue(Form f) throws FormException {
		Query q = new Query();
		q.setQuery("SELECT " + this.destinationColumn + " FROM " + this.destinationTable
					+ " WHERE " + f.getUniqueKeyName() + "=?");
		q.setValues(new String[]{f.getFormParameters().getUniqueKeyValue()});
		GenericResultSet grs = null;
		try {
			grs = Settings.getRepository().getApplicationDataSource(this.destinationDataSourceId).runQuery(q);
		} catch (DataSourceException e) {
			throw new FormException(e.toString());
		}
		if (grs.getNumberOfRows() > 0){
			originalValues = new String[grs.getNumberOfRows()];
			for(int i = 0; grs.nextRow(); i++){
				this.originalValues[i] = grs.getRow()[0];
			}			
		}
		
	}

}
